package com.example.lib_core.util.presenter

import android.app.Activity
import android.graphics.Rect
import android.view.ViewTreeObserver

/**
 * 用于监听布局变化的回调类
 */
class GlobalLayoutListenerImp(private val activity: Activity) : ViewTreeObserver.OnGlobalLayoutListener {

    private val iKeyBoardCallbackList = mutableListOf<IKeyBoardCallback>()
    private val status = NONE

    /** 全屏时的高度 */
    private var fullScreenHeight = -1
    /** 状态栏高度 */
    private var statusBarHeight = -1


    override fun onGlobalLayout() {
        //获取可视范围
        val rect = Rect()
        activity.window.decorView.getWindowVisibleDisplayFrame(rect)
        //获取屏幕高度
        val screenHeight = getFullScreenHeight(activity)
        //获取状态栏高度
        val statueHeight = getStatueBarHeight(activity)
        //获取被遮挡高度（键盘高度）(屏幕高度-状态栏高度-可视范围)
        val keyBoardHeight: Int = screenHeight - statusBarHeight - rect.height()
        //显示或者隐藏
        val isKeyBoardShow = keyBoardHeight >= screenHeight / 3
        //当首次或者和之前的状态不一致的时候会回调，反之不回调(用于当状态变化后才回调，防止多次调用)

    }

    /**
     * 用于获取全屏时的整体高度
     *
     * @return 屏幕高度
     */
    private fun getFullScreenHeight(activity: Activity): Int {
        if (fullScreenHeight == -1){
            val vm = activity.windowManager
            fullScreenHeight = vm.defaultDisplay.height
        }
        return fullScreenHeight
    }

    /**
     * 用于获取状态栏高度
     *
     * @return 状态栏高度
     */
    private fun getStatueBarHeight(activity: Activity): Int {
        if (statusBarHeight == -1){
            val res = activity.resources
            val resId = res.getIdentifier("status_bar_height", "dimen", "android")
            statusBarHeight =  res.getDimensionPixelSize(resId)
        }
        return statusBarHeight;
    }

    companion object {
        private const val NONE = 0;
        private const val SHOW = 1;
        private const val HIDDEN = 2;
    }
}